#include"../logs/bitlog.hpp"
using namespace bitlog;

void bench(const string& logger_name,size_t thread_count,size_t msg_count,size_t msg_len){
    //1. 获取日志器
    Logger::ptr lp=GetLogger(logger_name);
    if(lp.get()==nullptr) return;
    //2. 组织指定长度的日志消息
    string msg(msg_len,'1');
    //3. 创建指定数量的线程
    size_t msg_count_per_thread=msg_count/thread_count;
    vector<thread> threads;
    vector<double> cost_time(thread_count);
    for(int i=0;i<thread_count;i++){
        //4. 线程函数内部开始计时
        threads.emplace_back([&](){
            auto start=std::chrono::high_resolution_clock::now(); 
            //5. 开始循环写日志
            for(size_t j=0;j<msg_count_per_thread;j++){
                lp->fatal("%s",msg);
            }
            //6. 线程函数内部结束计时
            auto end=std::chrono::high_resolution_clock::now();
            auto cost=std::chrono::duration_cast<std::chrono::duration<double>>(end-start);
            cost_time[i]=cost.count();       
            auto avg=msg_count_per_thread/cost_time[i];
            cout<<"线程"<<i<<"耗时："<<cost.count()<<"s";
            cout<<" 平均："<<(size_t)avg<<"/s\n";
        });
    }
    for(auto& e:threads){
        e.join();
    }
    //7. 计算总耗时
    auto max_cost=0;
    for(auto cost:cost_time) max_cost=max_cost>cost?max_cost:cost;
    //8. 进行输出打印
    cout<<"总耗时："<<max_cost<<endl;
    cout<<"平均每秒输出："<<(size_t)(msg_count/max_cost)<<endl;
}
void sync_bench(size_t thread_count,size_t msg_count,size_t msg_len){
    static int num=1;
    string logger_name="sync_bench_logger"+to_string(num++);
    LOGI("********************************************");
    LOGI("同步日志器测试：%d threads, %d messages",thread_count,msg_count);

    GlobalLoggerBuilder::ptr lbp(new GlobalLoggerBuilder);
    lbp->buildLoggerName(logger_name);
    lbp->buildSinks<FileSink>("./logs/sync.log");
    lbp->buildLoggerType(Logger::Type::LOGGER_SYNC);
    lbp->build();
    bench(logger_name,thread_count,msg_count,msg_len);

    LOGI("**********************************************");
}
void async_bench(size_t thread_count,size_t msg_count,size_t msg_len){
    static int num=1;
    string logger_name="sync_bench_logger"+to_string(num++);
    LOGI("********************************************\n");
    LOGI("异步日志器测试：%d threads, %d messages\n",thread_count,msg_count);

    GlobalLoggerBuilder::ptr lbp(new GlobalLoggerBuilder);
    lbp->buildLoggerName(logger_name);
    lbp->buildSinks<FileSink>("./logs/sync.log");
    lbp->buildLoggerType(Logger::Type::LOGGER_NSYNC);
    lbp->build();
    bench(logger_name,thread_count,msg_count,msg_len);

    LOGI("**********************************************\n");
}
void bench_test(){
    //同步写日志
    sync_bench(1,100,100);
    sync_bench(5,100,100);
    //异步写日志
    async_bench(1,100,100);
    async_bench(5,100,100);
}
int main(){
    bench_test();
    return 0;
}